<?php

namespace App\Http\Controllers\Dashboard;

use App\Http\Requests\Dashboard\NextCourseRequest;
use App\Http\Requests\Dashboard\SkillCourseStoreRequest;
use App\Http\Requests\Dashboard\SkillCourseUpdateRequest;

use App\Http\Resources\Dashboard\SkillCoursesResource;
use App\Models\Course;
use App\Models\Skill;
use App\Http\Controllers\Controller;
use App\Models\SkillCourse;
use Illuminate\Support\Arr;

class SkillCourseController extends Controller
{
    public function detail(Skill $skill, Course $course)
    {
        return $skill->courses()->where('course_id', $course->id)->withPivot('complete_percentage')->first();
    }

    public function skills(Course $course)
    {
        return $course->skills;
    }

    public function courses(Skill $skill)
    {
        return SkillCoursesResource::collection($skill->courses()->sortType()->get());
    }

    public function relation(Skill $skill, Course $course)
    {
        $relation = $skill->courses()->find($course->id);
        $next = $relation->pivot->next_course_id;
        $query = $skill->courses()
            ->where(function ($query) use ($next, $skill) {
                $query->whereJsonContains('next_course_id', $skill->id)//当前节点的先前节点
                ->orWhereIn('course_id', Arr::wrap($next));//当前节点的后继节点
            })
            ->where('course_id', '!=', $skill->id)//不包含本节点
            ->get();
        return new SkillCoursesResource($query);
    }

    public function attach(SkillCourseStoreRequest $request, Skill $skill, Course $course)
    {
        $skill->courses()->attach($course->id, $request->validated());
    }

    public function update(SkillCourseUpdateRequest $request, Skill $skill, Course $course)
    {
        $skill->courses()->updateExistingPivot($course->id, $request->validated());
    }
    public function addNextCourse(NextCourseRequest $request, Skill $skill,Course $course)
    {
        $skillCourse = SkillCourse::whereSkillId($skill->id)->whereCourseId($course->id)->first();
        $next = array_values(array_unique(array_merge($skillCourse->next_course_id??[], [intval($request->next_course_id)])));

        $skill->courses()->updateExistingPivot($course->id, ['next_course_id' => $next]);

    }

    public function deleteNextCourse(NextCourseRequest $request, Skill $skill,Course $course)
    {
        $skillCourse = SkillCourse::whereSkillId($skill->id)->whereCourseId($course->id)->first();

        $next = array_values(array_filter($skillCourse->next_skill_id, function ($item) use ($request) {
            return $item != $request->next_course_id;
        }));
        $skill->courses()->updateExistingPivot($course->id, ['next_course_id' => $next]);

    }
    public function detach(Skill $skill, Course $course)
    {
        $skill->courses()->detach($course->id);
    }
}
